package com.cupk.rotaryguard.monitor.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cupk.common.base.config.RedisKeyContant;
import com.cupk.common.base.utils.result.Result;
import com.cupk.common.base.utils.result.ResultGenerator;
import com.cupk.rotaryguard.monitor.entity.DeviceMonitorRecord;
import com.cupk.rotaryguard.monitor.mapper.MonitorRecordMapper;
import com.cupk.rotaryguard.monitor.service.MonitorRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author tjy
 * @date 2023/4/1
 * @apiNote
 */
@Service
@Slf4j
public class MonitorRecordServiceImpl extends ServiceImpl<MonitorRecordMapper, DeviceMonitorRecord>
        implements MonitorRecordService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MonitorRecordMapper monitorRecordMapper;

    /**
     * 查询所有监控记录
     *
     * @return
     */
    @Override
    public Result getMonitorRecords() {
        String recordJson = stringRedisTemplate.opsForValue().get(RedisKeyContant.DEVICE_RECORD);
        if (StringUtils.isNotBlank(recordJson)) {
            List<DeviceMonitorRecord> records = JSONArray.parseArray(recordJson, DeviceMonitorRecord.class);
            return ResultGenerator.genSuccessResultPage(records, records.size());
        }
        List<DeviceMonitorRecord> records = monitorRecordMapper.selectList(null);
        if (ObjectUtils.isNotEmpty(records)) {
            String deviceJson = JSON.toJSONString(records);
            stringRedisTemplate.opsForValue().set(RedisKeyContant.DEVICE_RECORD, deviceJson, RedisKeyContant.DEVICES_RECORD_TTL, TimeUnit.MINUTES);
            return ResultGenerator.genSuccessResultPage(records, records.size());
        }
        return ResultGenerator.genFailResult(null, "暂无结果");
    }

    @Override
    public Result getMonitorRecordById(Long id) {
        String recordJson = stringRedisTemplate.opsForValue().get(RedisKeyContant.DEVICE_RECORD + ":" + id);
        if (StringUtils.isNotBlank(recordJson)) {
            DeviceMonitorRecord record = JSONObject.parseObject(recordJson, DeviceMonitorRecord.class);
            return ResultGenerator.genSuccessResult(record, "获取成功");
        }
        DeviceMonitorRecord record = monitorRecordMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(record)) {
            recordJson = JSON.toJSONString(record);
            stringRedisTemplate.opsForValue().set(RedisKeyContant.DEVICE_RECORD + ":" + id, recordJson, RedisKeyContant.DEVICES_RECORD_TTL, TimeUnit.MINUTES);
            return ResultGenerator.genSuccessResult(record);
        }
        return ResultGenerator.genFailResult(null, "暂无结果");
    }

    /**
     * 删除监控记录
     *
     * @param ids
     * @return
     */
    @Override
    public Result delMonitorRecords(List<Integer> ids) {
        monitorRecordMapper.deleteBatchIds(ids);
        stringRedisTemplate.delete(RedisKeyContant.DEVICE_RECORD);
        return ResultGenerator.genSuccessResult(null, "删除成功");
    }

    /**
     * 根据设备id获取监控记录(记录时间倒序)
     *
     * @param deviceId
     * @return
     */
    @Override
    public Result getMonitorRecordByDeviceId(Integer pageNum, Integer pageSize, Long deviceId) {
        QueryWrapper<DeviceMonitorRecord> queryWrapper = new QueryWrapper<>();
        if (deviceId == null) {
            queryWrapper.orderByDesc("record_time");
            IPage<DeviceMonitorRecord> pageDate = new Page<>(pageNum, pageSize);
            IPage<DeviceMonitorRecord> deviceMonitorRecordIPage = monitorRecordMapper.selectPage(pageDate, queryWrapper);
            return ResultGenerator.genSuccessResult(deviceMonitorRecordIPage, "查询成功");
        }
        queryWrapper.eq("device_id", deviceId).orderByDesc("record_time");
        IPage<DeviceMonitorRecord> pageDate = new Page<>(pageNum, pageSize);
        IPage<DeviceMonitorRecord> deviceMonitorRecordIPage = monitorRecordMapper.selectPage(pageDate, queryWrapper);
        return ResultGenerator.genSuccessResult(deviceMonitorRecordIPage, "查询成功");
    }

    /**
     * 根据设备id获取最新监控记录
     *
     * @param deviceId
     * @return
     */
    @Override
    public Result getLatestMonitorRecordByDeviceId(Long deviceId) {
        QueryWrapper<DeviceMonitorRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", deviceId).orderByDesc("record_time");
        List<DeviceMonitorRecord> records = monitorRecordMapper.selectList(queryWrapper);
        if (records.size() != 0) {
            return ResultGenerator.genSuccessResult(records.get(0), "获取成功");

        }
        return ResultGenerator.genFailResult(null, "暂无数据");
    }

    @Override
    public Result delMonitorRecordById(Integer id) {
        monitorRecordMapper.deleteById(id);
        stringRedisTemplate.delete(RedisKeyContant.DEVICE_RECORD);
        return ResultGenerator.genSuccessResult("删除：" + id, "删除成功");
    }

    /**
     * 获取指定设备号的最新五百条数据用于状态诊断
     *
     * @param deviceId
     * @return
     */
    @Override
    public Result lastFiftyRecords(Long deviceId) {
        QueryWrapper<DeviceMonitorRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", deviceId)
                .orderByDesc("record_time")
                .last("limit 0,3500");
        List<DeviceMonitorRecord> curDeviceLastFiftyRecords = monitorRecordMapper.selectList(queryWrapper);
        return ResultGenerator.genSuccessResult(curDeviceLastFiftyRecords, "success");
    }

    /**
     * 获取指定设备最新10条数据用于展示
     *
     * @param deviceId
     * @return
     */
    @Override
    public Result getTenRecordByDeviceId(Long deviceId) {
        QueryWrapper<DeviceMonitorRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", deviceId)
                .orderByDesc("record_time")
                .last("limit 0,20");
        List<DeviceMonitorRecord> curDeviceLastTenRecords = monitorRecordMapper.selectList(queryWrapper);
        return ResultGenerator.genSuccessResult(curDeviceLastTenRecords, "获取成功");
    }
}
